package com.samuel.blog.controller.admin;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.samuel.blog.bean.PageBean;
import com.samuel.blog.constant.CommonConstant;
import com.samuel.blog.controller.BaseController;
import com.samuel.blog.entity.AuthorEntity;
import com.samuel.blog.entity.TagEntity;
import com.samuel.blog.service.AuthorService;
import com.samuel.blog.service.TagService;
import com.samuel.blog.utils.ResponseWriteUtils;
import com.samuel.blog.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Optional;

/**
 * <p>
 *
 * </p>
 *
 * @author kaiji
 * @since 2019/11/17 21:14
 */
@Controller
@RequestMapping("admin/tag")
public class TagController extends BaseController {

    private static final long serialVersionUID = -6406150003674981136L;

    private static final String PRE_PAGER = "admin/tag_";
    private static final Logger logger = LoggerFactory.getLogger(TagController.class);

    @Resource(name = "tagService")
    private TagService tagService;
    @Resource(name = "authorService")
    private AuthorService authorService;


    @GetMapping("/list" + SUFFIX)
    public String toList(HttpServletRequest request) {
        this.configCss(request, "tag", "tagList");
        return PRE_PAGER + LIST;
    }

    @ResponseBody
    @PostMapping("list" + SUFFIX)
    public String list(HttpServletRequest request, PageBean pageBean, HttpServletResponse response) {
        this.configCss(request, "tag", "tagList");

        PageInfo<TagEntity> selectPage = tagService.selectPage(pageBean, null);
        if (selectPage.getList() != null && selectPage.getList().size() > 0) {
            selectPage.getList().forEach(tagEntity -> {
                AuthorEntity authorEntity = authorService.selectById(tagEntity.getAuthorId());
                String authorName = Optional.ofNullable(authorEntity)
                		.map(author->authorEntity.getUserName()).orElse("");
                tagEntity.setAuthorName(authorName);
            });
        }
        this.returnTableData(pageBean, selectPage, response);
        return null;
    }

    @ResponseBody
    @PostMapping("update" + SUFFIX)
    public String update(HttpServletRequest request, HttpServletResponse response, TagEntity tagEntity) {
        this.configCss(request, "tag", "tagList");
        String message = "修改标签成功！";
        logger.info("开始验证===>修改标签");
        if (null == tagEntity) {
            message = "标签名称不能为空！";
            logger.warn(message);
            this.ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, message);
            return null;
        }

        if (StringUtils.empty(tagEntity.getName())) {
            logger.warn("请填写标签名称！");
            this.ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, "请填写标签名称！");
            return null;
        }

        // 查询角色名称是否重复
        TagEntity tag = tagService.selectByName(tagEntity.getName());
        if (null != tag && !tag.getTagId().equals(tagEntity.getTagId())) {
            message = "标签名称重复！";
            logger.warn(message);
            this.ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, message);
            return null;
        }
        logger.info("结束验证===>标签实体类");

        tagEntity.setModifyDate(new Date());

        int num = tagService.updateById(tagEntity);
        if (num > 0) {
            logger.error(message);
            this.ajax(response, CommonConstant.NoticeCode.SUCCESS_ONE, message);
        } else {
            message = "修改标签失败！";
            logger.error(message);
            this.ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, message);
        }
        return null;
    }

    @ResponseBody
    @PostMapping("save" + SUFFIX)
    public String save(HttpServletRequest request, HttpServletResponse response, TagEntity tagEntity) {

        this.configCss(request, "tag", "tagList");

        String message = "保存标签成功！";
        logger.info("开始验证===>保存标签");
        if (null == tagEntity) {
            message = "标签名称不能为空！";
            logger.warn(message);
            this.ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, message);
            return null;
        }

        if (StringUtils.isNotEmpty(tagEntity.getTagId())) {
            message = "这是一个保存标签方法！";
            logger.warn(message);
            this.ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, message);
            return null;
        }

        if (StringUtils.empty(tagEntity.getName())) {
            logger.warn("请填写标签名称！");
            this.ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, "请填写标签名称！");
            return null;
        }

        // 查询标签名称是否重复 如果重复 就返回id
        TagEntity tag = tagService.selectByName(tagEntity.getName());
        if (null != tag) {
            JSONObject obj = new JSONObject();
            obj.put("success", CommonConstant.NoticeCode.SUCCESS_ONE);
            obj.put("message", "保存成功！");
            obj.put("id", tag.getTagId());
            ResponseWriteUtils.writeJson(response, obj.toString());
            return null;
        }
        logger.info("结束验证===>标签实体类");

        tagEntity.setCreateDate(new Date());
        AuthorEntity authorEntity = (AuthorEntity)this.getSessionByKey(request, CommonConstant.USER_LOGIN_SESSION_KEY);
        tagEntity.setAuthorId(authorEntity.getAuthorId());

        int num = tagService.insert(tagEntity);
        if (num > 0) {
            JSONObject obj = new JSONObject();
            obj.put("success", CommonConstant.NoticeCode.SUCCESS_ONE);
            obj.put("message", "保存成功！");
            obj.put("id", tagService.selectByName(tagEntity.getName()).getTagId());
            ResponseWriteUtils.writeJson(response, obj.toString());
            return null;
        } else {
            message = "保存标签失败！";
            logger.error(message);
            this.ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, message);
        }

        return null;
    }

    @PostMapping("delete")
    public String delete(HttpServletResponse response, String tagId, String articleId) {
        int num = tagService.deleteAndArticle(tagId, articleId);
        if (num == 0) {
            this.ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, "删除标签失败");
        } else {
            this.ajax(response, CommonConstant.NoticeCode.SUCCESS_ONE, "删除标签成功！");
        }
        return null;
    }

}
